package com.bigknow.appstore.web.console.controller;

import com.bigknow.appstore.proxy.entity.ProxyMeta;
import com.bigknow.appstore.proxy.service.ProxyManager;
import com.bigknow.appstore.web.console.app.Application;
import com.bigknow.appstore.web.console.app.ApplicationCategory;
import com.bigknow.appstore.web.console.service.IApplicationCategoryService;
import com.bigknow.appstore.web.console.service.IApplicationService;
import com.bigknow.appstore.web.framework.controller.AbstractRestController;
import com.bigknow.appstore.web.framework.vo.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.Comparator;
import java.util.List;

@RestController
@RequestMapping(value = "/sys/applicationCategory")
public class ApplicationCategoryController extends AbstractRestController<ApplicationCategory, IApplicationCategoryService> {

    @Autowired
    protected ProxyManager proxyManager;

    @Override
    protected String getBasePath() {
        return "sys";
    }

    @Override
    protected String getBaseName() {
        return "applicationCategory";
    }

    @RequestMapping(value = "rest/findAllProxyMeta", method = RequestMethod.GET)
    public List<ProxyMeta> findAllProxyMeta() {
        return proxyManager.findAllProxyMeta();
    }

    @RequestMapping(value = "/list")
    public ModelAndView list(ApplicationCategory applicationCategory, Integer pageIndex, Integer pageSize) {
        ModelAndView mv = super.list(applicationCategory, pageIndex, pageSize);
        List<ApplicationCategory> categories = ((Page) mv.getModel().get("page")).getEntities();
        categories.sort(Comparator.comparingInt(c -> c.getSort()));
        for (ApplicationCategory category : categories) {
            category.setFuzzyField(String.valueOf(service.getAppCount(category)));
        }
        return mv;
    }
}